package websocket

import (
	"net/http"

	"github.com/gorilla/websocket"
)

// 这里可以添加其他必要的方法或函数

var defaultServer *WebSocketServer

// GetDefaultServer 获取默认的WebSocket服务器实例
func GetDefaultServer() *WebSocketServer {
	return defaultServer
}

// SetDefaultServer 设置默认的WebSocket服务器实例
func SetDefaultServer(server *WebSocketServer) {
	defaultServer = server
}

// NewWebSocketServerInstance 创建一个新的WebSocket服务器实例
func NewWebSocketServerInstance(addr string) *WebSocketServer {
	server := &WebSocketServer{
		Rooms:     make(map[string]*Room),
		GameRooms: make(map[string]*GameRoom),
		upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		},
	}

	return server
}

// SetHandler 设置HTTP处理器
func (s *WebSocketServer) SetHandler(handler http.Handler) {
	// 这里简化处理，实际项目中可能需要更复杂的逻辑
}

// ServeHTTP 实现http.Handler接口
func (s *WebSocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 处理WebSocket连接
	if r.URL.Path == "/ws" {
		// 从查询参数中获取必要的参数
		userID := r.URL.Query().Get("user_id")
		roomID := r.URL.Query().Get("room_id")
		userName := r.URL.Query().Get("user_name")
		s.ServeWS(w, r, userID, roomID, userName)
		return
	}

	// 否则返回404
	http.Error(w, "Not found", http.StatusNotFound)
}
